<template>
  <div id="app" class="outer-container">
    <div class="container" ref="container">
      <div class="chat-container" ref="chatContainer">
        <div v-for="(message, index) in messages" :key="index" :class="[message.role + '-message', 'message-container']">
          <div class="avatar" v-if="message.role === 'user'"></div>
          <div class="avatar" v-if="message.role === 'assistant'"></div>
          <div class="message-content" :class="message.role + '-message-content'">
            {{ message.content }}
          </div>
        </div>
      </div>
    </div>
    <div class="input-container">
      <input v-model="newMessage" placeholder="Type your message..." @keydown.enter="handleEnterKey" class="message-input">
      <button @click="sendMessage" class="send-button">Send</button>
    </div>
  </div>
</template>

<script>
import { chat } from '@/api/ai/gptKey';

export default {
  data() {
    return {
      messages: [],
      newMessage: '',
      content: '',
      initMessage: false,
    };
  },
  created() {
    this.connectWebSocket();
  },
  methods: {
    connectWebSocket() {
      const socketUrl = 'ws://localhost:8080/ai/socket/123';
      this.socket = new WebSocket(socketUrl);

      this.socket.onopen = () => {
        console.log('WebSocket connection opened');
      };

      this.socket.onmessage = (event) => {
        let message = JSON.parse(event.data);

        try {
          if (typeof message === 'string') {
            message = JSON.parse(message);
          }
          if (message.hasOwnProperty('error')) {
            this.$modal.msgError(message.error.message);
          } else {
            if(message.choices[0].delta.hasOwnProperty('content')){
              this.content += message.choices[0].delta.content;
              if (this.initMessage) {
                this.messages.push({
                  content: this.content,
                  role: 'assistant',
                });
                this.initMessage = false;
              } else {
                this.messages[this.messages.length - 1].content = this.content;
              }
            }
            
          }
        } catch (e) {}

      };

      this.socket.onclose = () => {
        console.log('WebSocket connection closed');
      };

      this.socket.onerror = (error) => {
        console.error('WebSocket error:', error);
      };
    },
    sendMessage() {
      if (this.newMessage.trim() === '') return;
      this.messages.push({
        id: this.messages.length + 1,
        content: this.newMessage,
        role: 'user',
      });
      this.newMessage = '';

      this.initMessage = true;
      this.content = '';

      chat({
        userId: 123,
        nickname: 'dongfaqing',
        messages: this.messages,
        type: 3,
      }).then((res) => {
        console.log(res);
        this.$modal.msgSuccess('发送成功');
      });
    },
    scrollToBottom() {
      const container = this.$refs.container;
      container.scrollTop = container.scrollHeight;
    },
    handleEnterKey(event) {
      if (!event.shiftKey) {
        event.preventDefault();
        this.sendMessage();
      }
    },
  },
  updated() {
    this.$nextTick(this.scrollToBottom);
  },
};
</script>

<style scoped>
#app {
  display: flex;
  flex-direction: column;
  height: 85vh;
  margin: 20px;
}

.outer-container {
  flex: 1;
  overflow-y: auto;
  position: relative;
}

.container {
  padding: 10px 50px;
  overflow-y: auto;
  height: 100%;
}

.chat-container {
  overflow-y: auto;
}

.message-container {
  display: flex;
  margin: 10px 0;
}

.avatar {
  width: 50px;
  height: 50px;
  border-radius: 50%;
  background-color: #ccc;
  margin-right: 10px;
}

.message-content {
  padding: 10px;
  margin: 5px;
  border-radius: 5px;
  position: relative;
  width:100%
}

.user-message-content {
  background-color: #f0f0f0;
}

.assistant-message-content {
  background-color: #e0e0e0;
}

.input-container {
  display: flex;
  align-items: center;
  padding-top: 10px;
  margin-top: 20px;
  margin-bottom: 20px;
  padding-left: 50px;
  padding-right: 50px;
}

.message-input {
  flex: 1;
  padding: 8px;
  border: 1px solid #ccc;
  border-radius: 5px;
  resize: none;
}

.send-button {
  margin-left: 10px;
  padding: 12px;
  border: 1px solid #007BFF;
  border-radius: 5px;
  background-color: #007BFF;
  color: white;
  cursor: pointer;
}
</style>
